<template>
  <div>
    <div class="demo-upload-list" v-if="src">
      <img :src="src" />
      <div class="demo-upload-list-cover">
        <i-icon type="ios-eye-outline" @click.native="preview()"></i-icon>
      </div>
    </div>
    <i-upload
        ref="upload"
        name="files"
        class="image-uploader"
        :show-upload-list="false"
        :on-success="handleSuccess"
        :format="['jpg','jpeg','png']"
        :max-size="2048"
        :on-format-error="handleFormatError"
        :on-exceeded-size="handleMaxSize"
        :action="uploadUrl"
        style="display: inline-block;width:58px;">
        <div style="width: 58px;height:58px;line-height: 58px;">
            <Icon type="camera" size="20"></Icon>
        </div>
    </i-upload>
    <i-modal title="查看图片" v-model="visible" width="800px">
      <img :src="src" v-if="visible" style="width: 100%" />
      <div slot="footer"></div>
    </i-modal>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      visible: false,
      src: null
    }
  },
  computed: {
    ...mapGetters({
      uploadUrl: 'uploadUrl'
    })
  },
  props: ['path'],
  methods: {
    preview() {
      this.visible = true
    },
    handleSuccess(res, file) {
      const path = res[0]
      this.$emit('update:path', path)
      this.setSrc(path)
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc:
          '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
      })
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
      })
    },
    setSrc(path) {
      this.src = path ? new URL(path, this.uploadUrl) : null
    }
  },
  watch: {
    path(val) {
      this.setSrc(val)
    }
  },
  mounted() {
    this.setSrc(this.path)
  }
}
</script>
<style lang="less">
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}

.image-uploader {
  .ivu-upload-select {
    background: #fff;
    border: 1px dashed #d7dde4;
    border-radius: 4px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.2s ease;
  }
}
</style>
